// 认证相关API服务
const BASE_URL = 'http://localhost:8000/auth';

export const authApi = {
  // 基础请求方法
  async request(options) {
    try {
      const token = uni.getStorageSync('token');
      const response = await uni.request({
        ...options,
        header: {
          'Authorization': token ? `Bearer ${token}` : '',
          ...options.header
        }
      });

      // 处理401状态码
      if (response.statusCode === 401) {
        // 清除本地存储的token
        uni.removeStorageSync('token');
        uni.removeStorageSync('userInfo');
        
        // 跳转到登录页
        uni.reLaunch({
          url: '/pages/auth/login'
        });
        throw new Error('需要登录');
      }

      return response;
    } catch (error) {
      throw error;
    }
  },

  // 账号密码登录
  login(username, password) {
    return this.request({
      url: `${BASE_URL}/login`,
      method: 'POST',
      data: { username, password }
    });
  },

  // 获取微信登录URL
  async getWxLoginUrl() {
    const res = await this.request({
      url: `${BASE_URL}/wxLogin`,
      method: 'GET'
    });
    return res.data;
  },

  // 处理微信登录回调
  wxCallback(code, state = '') {
    // 从URL中获取state参数，仅在H5环境下执行
    // #ifdef H5
    if (!state && window.location.href.includes('state=')) {
      const stateMatch = window.location.href.match(/state=([^&]+)/);
      state = stateMatch ? stateMatch[1] : '';
    }
    // #endif
    
    return this.request({
      url: `${BASE_URL}/wxCallback`,
      method: 'GET',
      data: { 
        code,
        state: state || uni.getStorageSync('wx_state') || '' // 允许空state
      }
    });
  },

  // 退出登录
  logout() {
    return this.request({
      url: `${BASE_URL}/logout`,
      method: 'POST'
    });
  },

  // 刷新Token
  refreshToken() {
    return this.request({
      url: `${BASE_URL}/refresh`,
      method: 'POST'
    });
  },

  // 注册账号
  register(userData) {
    return this.request({
      url: `${BASE_URL}/register`,
      method: 'POST',
      data: userData
    });
  },

  // 重置密码
  resetPassword(email) {
    return this.request({
      url: `${BASE_URL}/reset-password`,
      method: 'POST',
      data: { email }
    });
  },

  // 验证重置密码的token
  verifyResetToken(token) {
    return this.request({
      url: `${BASE_URL}/verify-reset-token`,
      method: 'POST',
      data: { token }
    });
  },

  // 更新密码
  updatePassword(token, newPassword) {
    return this.request({
      url: `${BASE_URL}/update-password`,
      method: 'POST',
      data: { token, newPassword }
    });
  }
}; 